<template>
  <div class="sign-form-item">
    <div class="title">
      <div class="dot"/>分成信息<el-checkbox v-if="isModify" :disabled="disabledCheck" v-model="modifyPrice" class="modify-price-checkbox">修改分成信息</el-checkbox>
    </div>
    <el-form
      ref="formRef"
      :model="modelData"
      :rules="formRules"
      :label-width="labelWidth"
      class="lineHeight32"
      label-position="right">
      <el-row type="flex" class="response-el-row">
        <template v-if="isModify && modifyPrice">
          <el-col :span="24">
            <el-form-item label="调价原因" prop="adjustPriceReason">
              <el-input v-model="modelData.adjustPriceReason" :maxlength="1000" resize="none" class="width240" placeholder="请输入调价原因" type="textarea" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="rowSpan" style="transform: translateX(-10px); letter-spacing: -1px;">
            <el-form-item label="上次调价日期" prop="lastDate" label-width="110px">
              <el-date-picker v-model="modelData.lastDate" clearable value-format="timestamp" size="small" type="date" format="yyyy/MM/dd" style="width:240px" placeholder="上次调价日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="rowSpan" style="transform: translateX(-10px);">
            <el-form-item label="价格生效日期" prop="effectiveDate" label-width="110px">
              <el-date-picker v-model="modelData.effectiveDate" clearable value-format="timestamp" size="small" type="date" format="yyyy/MM/dd" style="width:240px" placeholder="价格生效日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="rowSpan">
            <el-form-item label="图文价格截图" prop="graphicPrice">
              <div class="width240">
                <upAttachment
                  :hide-confirm="true"
                  :file-list="modelData.graphicPrice"
                  import-api="admin/supplier/withdraw/upload"
                  btn-text="上传文件"
                  @complateSetData="complateSetData($event, 'graphicPrice')"
                  @removeFileList="removeFileList($event, 'graphicPrice')" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="rowSpan">
            <el-form-item label="视频价格截图" prop="videoPrice">
              <div class="width240">
                <upAttachment
                  :hide-confirm="true"
                  :file-list="modelData.videoPrice"
                  :is-disabled="isModify && !modifyPrice"
                  import-api="admin/supplier/withdraw/upload"
                  btn-text="上传文件"
                  @complateSetData="complateSetData($event, 'videoPrice')"
                  @removeFileList="removeFileList($event, 'videoPrice')" />
              </div>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="rowSpan">
          <el-form-item label="公司分成比例" prop="profitSharingRatio">
            <el-input
              v-model="modelData.profitSharingRatio"
              :disabled="isModify && !modifyPrice"
              name="deductionRate"
              class="width240"
              size="small"
              placeholder="请输入"
              type="number"
              oninput="if(value>100)value=100;if(value<0)value=0;"
              @input="numInputChange($event, 'profitSharingRatio')"
            >
              <span slot="suffix" style="margin-right:5px;color:#333;">%</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="达人分成比例" prop="talentSharingRatio">
            <el-input
              v-model="modelData.talentSharingRatio"
              disabled
              class="width240"
              size="small"
              placeholder="达人分成比例"
              type="number"
            >
              <span slot="suffix" style="margin-right:5px;color:#333;">%</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="分成说明" prop="profitSharingRemark">
            <el-input v-model="modelData.profitSharingRemark" :disabled="isModify && !modifyPrice" :maxlength="256" resize="none" class="width240" placeholder="请输入分成比例说明" type="text" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="返点比例" prop="rebateRatio">
            <el-input
              v-model="modelData.rebateRatio"
              :disabled="isModify && !modifyPrice"
              class="width240"
              size="small"
              placeholder="请输入"
              type="number"
              oninput="if(value>100)value=100;if(value<0)value=0;"
              @change="numberInputChange('rebateRatio')"
            >
              <span slot="suffix" style="margin-right:5px;color:#333;">%</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="对接人员" prop="dockingUsers">
            <selectWithUserLoad
              v-model="dockingUsers"
              :default-list="dockingUsers || []"
              :extend-params="{ userStatus: 1, type: 1 }"
              style="width:240px;"
              placeholder="请选择人员"
              key-name="id"
              value-type="object"
              label-name="userName"
              multiple
              filterable
              clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="保底金额(元)" prop="guaranteePrice">
            <el-input
              v-model="modelData.guaranteePrice"
              :disabled="isModify && !modifyPrice"
              name="guaranteePrice"
              class="width240"
              size="small"
              type="number"
              oninput="if(value>9999999999)value=9999999999;if(value<0)value=0;"
              placeholder="请输入"
              @input="numInputChange($event, 'guaranteePrice')"
              @mousewheel.native.prevent
            >
              <span slot="suffix" style="margin-right:5px;color:#333;">元</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="保底说明" prop="guaranteeRemark">
            <el-input v-model="modelData.guaranteeRemark" :disabled="isModify && !modifyPrice" :maxlength="256" resize="none" class="width240" placeholder="请输入保底金额说明" type="text" size="small" />
          </el-form-item>
        </el-col>
        <!-- <dynamicKey v-model="modelData.dynamicKey" /> -->
        <!-- 动态字段 -->
        <el-col v-for="(item) in modelData.dynamicKey" :key="item.name" :span="rowSpan">
          <el-form-item :prop="item.name">
            <el-tooltip slot="label" :content="item.name" placement="top" effect="dark">
              <div class="item ellipsisOne">
                {{ item.name }}
              </div>
            </el-tooltip>
            <dynamicKey :item="item" :is-disabled="isModify && !modifyPrice" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import upAttachment from '@/components/Common/upAttachment/index';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import math from '@/utils/math';
import dynamicKey from './dynamicKey';
export default {
  components: { upAttachment, dynamicKey, selectWithUserLoad },
  model: {
    prop: 'modelData',
    event: 'changeValue'
  },
  props: {
    modelData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    labelWidth: {
      type: String,
      default: '110px'
    },
    isModify: {
      type: Boolean,
      default: false
    },
    isModifyPrice: {
      type: Boolean,
      default: false
    },
    rowSpan: {
      type: Number,
      default: 12
    }
  },
  data() {
    return {
      modifyPrice: false, // 修改价格信息
      disabledCheck: false,
      baseModelData: {},
      isModifyPriceChange: false
    };
  },
  computed: {
    dockingUsers: {
      get() {
        return (this.modelData.dockingUsers || []).map(item => {
          return { id: item.id, userName: item.userName || item.name };
        });
      },
      set(list) {
        this.modelData.dockingUsers = list.map(item => {
          return { id: item.id, userName: item.userName || item.name };
        });
      }
    },
    modifyPriceInfoRules() {
      return {
        rebateRatio: [{ required: true, trigger: 'blur', message: '请输入返点比例' }],
        profitSharingRatio: [{ required: true, trigger: 'blur', message: '请输入公司分成比例' }]
      };
    },
    formRules() {
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
      return Object.assign(this.modelData.requiredModel || {}, this.modifyPriceInfoRules);
    }
  },
  watch: {
    isModifyPrice: {
      handler(val) {
        this.modifyPrice = val;
        this.disabledCheck = val;
      },
      immediate: true
    },
    modelData: {
      handler() {
        setTimeout(() => {
          !this.isModifyPriceChange && (this.baseModelData = _.cloneDeep(this.modelData));
          this.isModifyPriceChange = true;
        });
      },
      deep: true
    },
    'modelData.profitSharingRatio': {
      handler(val) {
        const talentNum = !val && val !== 0 ? null : math.subtract(100, Number(val)).toFixed(2);
        this.$set(this.modelData, 'talentSharingRatio', talentNum);
      },
      immediate: true,
      deep: true
    },
    modifyPrice(status) {
      // 勾选修改填写完数据又取消修改，恢复原始数据
      if (this.isModify && !status) {
        const cloneBaseModelData = _.cloneDeep(this.baseModelData);
        Object.keys(cloneBaseModelData).forEach(key => {
          if (key !== 'dynamicKey') {
            this.modelData[key] = cloneBaseModelData[key];
          }
        });
        ['adjustPriceReason', 'lastDate', 'effectiveDate', 'graphicPrice', 'videoPrice'].forEach(key => {
          this.modelData[key] = null;
        });
        if (cloneBaseModelData.dynamicKey && cloneBaseModelData.dynamicKey.length) {
          this.modelData.dynamicKey.forEach(i => {
            const item = cloneBaseModelData.dynamicKey.find(j => i.id === j.id);
            this.$set(i, 'value', item ? item.value : '');
          });
        }
        this.$emit('changeValue', this.modelData);
        this.$nextTick(() => {
          this.$refs.formRef.clearValidate();
        });
      }
    }
  },
  methods: {
    numberInputChange(key) {
      if (this.modelData[key]) this.modelData[key] = Number(this.modelData[key]).toFixed(2);
    },
    numInputChange(text, prop) {
      let str;
      str = text.replace(/[^\d.]/g, '');
      str = str.replace(/^0+(\d)/, '$1'); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
      str = str.replace(/\./g, ''); // 数量只允许输入0和正整数
      str = str === '' ? null : str;
      if (this.modelData[prop]) this.modelData[prop] = Number(str);
    },
    validateForm(validate = true) {
      return new Promise((resolve, reject) => {
        if (validate) {
          if (this.isModify && !this.modifyPrice) { // 未勾选状态默认不校验
            resolve(true);
            return;
          }
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject();
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    complateSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      fileList.url = typeof data === 'string' ? data : data.url;
      if (this.modelData[key]) {
        this.modelData[key].push(fileList);
      } else {
        this.$set(this.modelData, key, [fileList]);
      }
    },
    removeFileList({ file, index }, key) {
      this.modelData[key].splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>
.sign-form-item {
  &::v-deep {
    .el-form-item__label {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .el-form-item__error {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 240px;
    }
  }
}

.title {
  font-size: 16px;
  font-weight: 600;
  text-align: left;
  color: #333333;
  line-height: 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  .dot {
    width: 4px;
    height: 4px;
    background-color: #406EFF;
    margin-right: 6px;
  }
  .modify-price-checkbox {
    margin-left: 8px;
    ::v-deep .el-checkbox__label {
      padding-left: 2px;
    }
    ::v-deep .el-checkbox__inner {
      top: -1px;
    }
  }
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-select {
      width: 240px;
    }
    .el-input__inner {
      width: 240px;
    }
    .el-tag.el-tag--info {
      color: #406eff !important;
      background: #eff3fb;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
